package com.taoyibao.hongcanting.ui.home.activity;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;

import com.taoyibao.hongcanting.R;
import com.taoyibao.hongcanting.base.activity.BaseActivityPresenter;
import com.taoyibao.hongcanting.base.delegate.ToolbarDelegate;
import com.taoyibao.hongcanting.cache.SpUtils;
import com.taoyibao.hongcanting.constant.CodeConstant;
import com.taoyibao.hongcanting.constant.NetCode;
import com.taoyibao.hongcanting.dialog.DialogComment;
import com.taoyibao.hongcanting.event.EventCartClearAll;
import com.taoyibao.hongcanting.event.EventSubmitSuccess;
import com.taoyibao.hongcanting.event.EventUpdataCart;
import com.taoyibao.hongcanting.http.DefaultTransformer;
import com.taoyibao.hongcanting.http.JsonApiWrapper;
import com.taoyibao.hongcanting.http.ProgressSubscriber;
import com.taoyibao.hongcanting.model.CartSimpleInfoModel;
import com.taoyibao.hongcanting.model.CompanyBaseModel;
import com.taoyibao.hongcanting.model.ShoppingCartModel;
import com.taoyibao.hongcanting.ui.home.delegate.ShoppingCartDelegate;
import com.taoyibao.hongcanting.utils.CodeUtils;
import com.taoyibao.hongcanting.utils.LogUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

/**
 * @author TangAnna
 * @description: 购物车页面
 * @date :${DATA} 17:09
 */
public class ShoppingCartActivity extends BaseActivityPresenter<ShoppingCartDelegate> implements View.OnClickListener, ToolbarDelegate.OnRightClickListener {

    private String mResouce;//页面来源

    @Override
    protected Class<ShoppingCartDelegate> getDelegateClass() {
        return ShoppingCartDelegate.class;
    }

    @Override
    protected void bindEvenListener() {
        super.bindEvenListener();
        mResouce = getIntent().getStringExtra(CodeConstant.ACTIVITY_SOURCE);
        getShoppingCartData();
        getCartSimpleInfo();
        EventBus.getDefault().register(this);
        viewDelegate.get(R.id.tv_includShoppingCart_next).setOnClickListener(this);
        viewDelegate.get(R.id.tv_includShoppingCart_continueAdd).setOnClickListener(this);
        //清空
        viewDelegate.setOnRightClickListener(this);
    }

    /**
     * @param context
     * @param resouce 页面来源  如果是直接关闭页面没有其他操作可不用传值
     */
    public static void open(Context context, String resouce) {
        Intent intent = new Intent(context, ShoppingCartActivity.class);
        if (!TextUtils.isEmpty(resouce)) {
            intent.putExtra(CodeConstant.ACTIVITY_SOURCE, resouce);
        }
        context.startActivity(intent);
    }

    /**
     * 清空购物车
     */
    public void clearAll() {
        JsonApiWrapper.getApiService().cartClear(SpUtils.getToken(), SpUtils.getMemberId())
                .compose(new DefaultTransformer<CompanyBaseModel>())
                .subscribe(new ProgressSubscriber<CompanyBaseModel>(this, true) {
                    @Override
                    public void onNext(CompanyBaseModel companyBaseModel) {
                        if (companyBaseModel.code == NetCode.HTTP_200) {
                            viewDelegate.setEmptyView(true);
                            sendClearAll();
                        } else {
                            super.onNext(companyBaseModel);
                        }
                    }
                });
    }

    /**
     * 清空购物车发送消息
     */
    public void sendClearAll() {
        EventCartClearAll event = new EventCartClearAll();
        event.isClearAll = true;
        EventBus.getDefault().post(event);
    }

    /**
     * 网络请求购物车数据
     */
    public void getShoppingCartData() {
        JsonApiWrapper.getApiService().cartInfo(SpUtils.getToken(), SpUtils.getMemberId())
                .compose(new DefaultTransformer<CompanyBaseModel<List<ShoppingCartModel>>>())
                .subscribe(new ProgressSubscriber<CompanyBaseModel<List<ShoppingCartModel>>>(this, true) {
                    @Override
                    public void onNext(CompanyBaseModel<List<ShoppingCartModel>> shoppingCartModel) {
                        if (shoppingCartModel.code == NetCode.HTTP_200) {
                            viewDelegate.setData(shoppingCartModel.data);
                        } else {
                            if (shoppingCartModel.code != NetCode.HTTP_7010) {
                                super.onNext(shoppingCartModel);
                            }
                            viewDelegate.setEmptyView(true);
                        }
                        viewDelegate.setDataView();
                    }
                });
    }

    /**
     * 购物车变化时调用
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void shoppingEvent(EventUpdataCart eventUpdataCart) {
        LogUtils.dNormal("TAG", "购物车页面收到的菜品" + eventUpdataCart.toString());
        if (eventUpdataCart.dishModel.dish_count == 0) {//当数据为0的时候  网络从新请求数据刷新页面
            getShoppingCartData();
        }
        getCartSimpleInfo();
    }

    /**
     * 订单提交成功关闭此页面
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void shoppingEvent(EventSubmitSuccess eventUpdataCart) {
        if (eventUpdataCart.isSuccess) {
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_includShoppingCart_next://去下单
                SubmitOrdersActivity.open(this, "");
                break;
            case R.id.tv_includShoppingCart_continueAdd://继续点餐
                if (!TextUtils.isEmpty(mResouce)) {
                    MenuActivity.open(this);
                } else {
                    finish();
                }
                break;
        }
    }

    /**
     * 查询购物车简单数据
     */
    public void getCartSimpleInfo() {
        JsonApiWrapper.getApiService().cartSimpleInfo(SpUtils.getToken(), SpUtils.getMemberId())
                .compose(new DefaultTransformer<CompanyBaseModel<List<CartSimpleInfoModel>>>())
                .subscribe(new ProgressSubscriber<CompanyBaseModel<List<CartSimpleInfoModel>>>(this, false) {
                    @Override
                    public void onNext(CompanyBaseModel<List<CartSimpleInfoModel>> cartSimpleInfoModel) {
                        viewDelegate.setBottomData(cartSimpleInfoModel);
                    }
                });

    }

    /**
     * 右上角清空功能
     *
     * @param view
     */
    @Override
    public void onRightClick(View view) {
        DialogComment dialogComment = new DialogComment(CodeUtils.getIdString(R.string.cart_cleanAll), new DialogComment.DialogCommentInterfaca() {
            @Override
            public void onConfirmListener() {
                clearAll();
            }
        });
        dialogComment.showDilaog(getSupportFragmentManager(), "TAG");
    }
}
